package face.pay.sharing.imp;

import com.alibaba.fastjson.JSON;
import com.face.pay.IPayConfigServer;
import com.face.pay.WxApiConfig;
import face.pay.AbstractRedis;
import face.pay.constant.CacheKey;
import face.pay.constant.OrderType;
import face.pay.dao.CpnCardDetailInfoDao;
import face.pay.dao.EnterpriseInfoDao;
import face.pay.dao.OrderInfoDao;
import face.pay.dao.SharingAccountDao;
import face.pay.entity.CpnCardDetailInfo;
import face.pay.entity.CpnWxAppInfo;
import face.pay.entity.EnterpriseInfo;
import face.pay.entity.OrderInfo;
import face.pay.sharing.ISharingAccountService;
import face.pay.sharing.biz.AddSharingAccountBiz;
import face.pay.sharing.biz.OrderEndSharingBiz;
import face.pay.sharing.biz.SharingOrderBiz;
import face.pay.util.DateUtil;
import face.pay.vo.VSharingAccount;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import weixin.popular.api.CardAPI;
import weixin.popular.api.TokenAPI;
import weixin.popular.bean.card.code.checkcode.CodeCheckCodeResult;
import weixin.popular.bean.card.code.consume.CodeConsume;
import weixin.popular.bean.card.code.consume.CodeConsumeResult;
import weixin.popular.bean.card.code.get.CodeGetResult;

import java.util.*;

@Service
@Slf4j
public class SharingAccountServiceImpl implements ISharingAccountService {

    @Autowired
    EnterpriseInfoDao enterpriseInfoDao;

    @Autowired
    OrderInfoDao orderInfoDao;

    @Autowired
    CpnCardDetailInfoDao cpnCardDetailInfoDao;

    @Autowired
    SharingAccountDao sharingAccountDao;

    @Autowired
    public IPayConfigServer iWxPayConfigServer;

    @Autowired
    AddSharingAccountBiz addSharingAccountBiz;

    @Autowired
    SharingOrderBiz sharingOrderBiz;

    @Autowired
    OrderEndSharingBiz orderEndSharingBiz;

    @Autowired
    AbstractRedis abstractRedis;
    /**
     * 针对需要分账的定订单进行分账
     * 并且对优惠券 进行核销
     * @param body
     */

    @Override
    public void sharingAccount(String body)  {
        try{
            Thread.sleep(2000);
        }catch (Exception e){

        }

        OrderInfo order = JSON.parseObject(body,OrderInfo.class);

        Long orderId = order.getId();

        OrderInfo orderInfo = this.orderInfoDao.getById(orderId);

        log.info("收到分账订单"+body);
        Integer oemId    = orderInfo.getOemId();
        Integer mchUerId = orderInfo.getUserId();

        WxApiConfig wxApiConfig = this.iWxPayConfigServer.getConfig(oemId);
        EnterpriseInfo enterpriseInfo = this.enterpriseInfoDao.queryByUserId(mchUerId);

        if (!wxApiConfig.validate()) {
            log.error("oem 微信证书配置错误");
            return;
        }

        try {

            Integer status = orderInfo.getStatus();

            Integer sharing  = orderInfo.getSharing();

            String  type      =  orderInfo.getType();

            log.info("检测订单支付状态  status ："+status);
            log.info("检测订单分账状态  sharing："+sharing);

            log.info("检测订单类型 type："+type);
            /**
             *目前仅支持微信分账
             */
            if(new Integer(1).equals(status) && new Integer(0).equals(sharing) && OrderType.WECHAT.equals(type)){

                log.info("订单状态正常 可以分账");

                Long cardDetailId = orderInfo.getCardDetailId();

                CpnCardDetailInfo cpnCard =  new CpnCardDetailInfo();

                cpnCard.setOemId(oemId);
                cpnCard.setUserId(mchUerId);
                cpnCard.setId(cardDetailId);
                CpnCardDetailInfo cpnCardDetailInfo = this.cpnCardDetailInfoDao.getDetail(cpnCard);
                /**
                 * 核销优惠券
                 */

                if(cpnCardDetailInfo!=null){

                    Integer marketId = cpnCardDetailInfo.getMarketId();

                    /**
                     * 核销优惠券
                     */
                    consume(cpnCardDetailInfo);

                    Map<String,VSharingAccount> map= this.getSharingAccounts(wxApiConfig,enterpriseInfo.getWxSubMchId(),mchUerId,oemId,marketId);

                    if(map!=null){
                        log.info("分账");
                        String sharingNo = UUID.randomUUID().toString();
                        orderInfo.setSharingNo(sharingNo);
                        Boolean isSuccess =  this.sharingOrderBiz.sharing(wxApiConfig,orderInfo,enterpriseInfo,cpnCardDetailInfo,map);

                    }else{
                        orderInfo.setSharing(-1);
                        orderInfo.setSharingMessage("获取分账对象关系错误");
                    }
                    this.orderInfoDao.updatePayInfo(orderInfo);
                      /**
                     * 更新订单状态
                     */
                }else {
                    log.info("未找到该订单对应优惠券");
                    /**
                     * 分账存疑
                     */
                    orderInfo.setSharing(2);
                }


            }else {
                log.info("订单分账终止 状态");
            }

        }catch (Exception e){
           log.error("分账失败",e);
        }


    }


    public Map<String,VSharingAccount> getSharingAccounts(WxApiConfig wxApiConfig, String subMchId, Integer mchUserId, Integer oemId, Integer marketId){

        Map<String,VSharingAccount> map = new HashMap<>();

        List<VSharingAccount> list =  new ArrayList<>();

        /**
         * 检测 商家-->cpn 分账对象
         *
         */
        log.info("检测 商家-->cpn 分账对象");
        VSharingAccount cpnAccount = this.sharingAccountDao.getAccount("CPN",0,mchUserId);
        if(cpnAccount!=null ){
            Integer cpn_status = cpnAccount.getStatus();
            log.info("status:"+cpn_status);
            if(!new Integer(1).equals(cpn_status)){
                log.info("分账对象关系 尚未和微信 建立 ");
                /**
                 * 建立关系
                 */
                Boolean isSuccess =    addSharingAccountBiz.addAccount(wxApiConfig,subMchId,cpnAccount);
                if(!isSuccess){
                    return  null;
                }
            }
        }
        map.put("CPN",cpnAccount);

        log.info("检测 商家-->oem 分账对象");
        VSharingAccount oemAccount = this.sharingAccountDao.getAccount("OEM",oemId,mchUserId);
        if(oemAccount!=null ){
            Integer oem_status = oemAccount.getStatus();
            log.info("status:"+oem_status);
            if(!new Integer(1).equals(oem_status)){
                log.info("分账对象关系 尚未和微信 建立 ");
                /**
                 * 建立关系
                 */
              Boolean isSuccess =   addSharingAccountBiz.addAccount(wxApiConfig,subMchId,oemAccount);
              if(!isSuccess){
                  return  null;
              }
            }
            list.add(oemAccount);
        }
        map.put("OEM",oemAccount);

        log.info("检测 商家-->markrt 分账对象");
        VSharingAccount marketAccount = this.sharingAccountDao.getAccount("MARKET",marketId,mchUserId);
        if(marketAccount!=null ){
            Integer market_status = marketAccount.getStatus();
            log.info("status:"+market_status);
            if(!new Integer(1).equals(market_status)){
                log.info("分账对象关系 尚未和微信 建立 ");
                /**
                 * 建立关系
                 */
                Boolean isSuccess =    addSharingAccountBiz.addAccount(wxApiConfig,subMchId,marketAccount);
                if(!isSuccess){
                    return  null;
                }
            }
            list.add(marketAccount);
        }
        map.put("MARKET",marketAccount);


        return  map;

    }

  private Boolean consume(CpnCardDetailInfo cpnCardDetailInfo){

        log.info("核销优惠券");
        Object cpnApp = abstractRedis.get(CacheKey.WX_APP_INFO);
        if(cpnApp!=null){

            /**
             * 检测 优惠券状态
             */
            CpnWxAppInfo cpnWxAppInfo = JSON.parseObject(cpnApp.toString(),CpnWxAppInfo.class);

            Integer status = cpnCardDetailInfo.getStatus();
            log.info("优惠券状态:"+status);
            /**
             * 未核销的都可以核销
             */
            if(!new Integer(4).equals(status)){
                String token = cpnWxAppInfo.getAccess_token();

                log.error("token:"+token);
                CodeConsume codeConsume =  new CodeConsume();
                String  cardId = cpnCardDetailInfo.getWxCardId();
                String  code =  cpnCardDetailInfo.getCode();

                log.info("CardId："+cardId);
                log.info("code："+code);

                codeConsume.setCardId(cpnCardDetailInfo.getWxCardId());
                codeConsume.setCode(cpnCardDetailInfo.getCode());

                CodeConsumeResult codeConsumeResult =  CardAPI.codeConsume(token,codeConsume);

                Boolean isSuccess  =  codeConsumeResult.isSuccess();

                log.info("核销结果:"+isSuccess);
                log.info("核销结果Errcode:"+codeConsumeResult.getErrcode());

            }
        }

        return  true;
  }

}
